package com.sibbay.tools;

import java.util.HashMap;

import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;

public final class Sharable implements Parcelable {

	private Object mObject;
	
    public static final Parcelable.Creator<Sharable> CREATOR = new Parcelable.Creator<Sharable>() {
        public Sharable createFromParcel(Parcel in) {
            return new Sharable(in);
        }

		@Override
		public Sharable[] newArray(int size) {
			return new Sharable[size];
		}
    };

	public Sharable(final Object obj) {
		mObject = obj;
	}

    public Sharable(Parcel in) {
        readFromParcel(in);
    }
	
    public Object obj() {
    	return mObject;
    }
    
	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(final Parcel out, int flags) {
		final long val = SystemClock.elapsedRealtime();
		out.writeLong(val);
		put(val, mObject);
	}
	
    private void readFromParcel(final Parcel in) {
    	final long val = in.readLong();
    	mObject = get(val);
    }

    /////
    
	private static final HashMap<Long, Object> sSharableMap = new HashMap<Long, Object>(3);

	synchronized private static void put(long key, final Object obj) {
		sSharableMap.put(key, obj);
	}
	
	synchronized private static Object get(long key) {
		return sSharableMap.remove(key);
	}
}
